package com.detroitchow;

/** 
 * MapScreen
 * Layouts out StoreItems on Map, IMplements LocationManager functionality, Implements Balloon functionality
 * 
 * 
 * ToDO: Come up with a way to manage test and production Google API ID's
 * 
 * Note:
 * When StoreVO.storeId = StoreVO.mapgroupId than store will be displayed oin screen
 * if they are not equal that means that store is within a grouping (ie. RenCen, MGM grand)
 * A unique store that is apart of a grouping will only show on map when clicked directly from Main screen
 * 
 */


import java.util.ArrayList;
import java.util.List;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.PopupWindow;

public class MapScreen extends MapActivity implements LocationListener  {

	public static final String INTENT_KEY="detroitChowMapAcgtivityIntentKey";
	private String selectedMapInent=null;
	private LocationManager locationManager;
	private MapView mapView;
	private MapController mapController;
	Drawable blackMarker;
	MyItemizedOverlay itemizedOverlay;
	MyLocationOverlay locationItemizedOverlay;
	PopupWindow popup = null;
	private StoreService storeService= null;
	ArrayList<StoreVO> stores =null;
	StoreVO selectedStore=null;
	private GeoPoint geoPoint;
	Drawable locationIcon;
	private MyOverlayItem overlayitem;
	protected Handler taskHandler = new Handler();
	private ProgressDialog pd;
	private int locationDurationCheck=0;
	private boolean isLocationCheckComplete=false;
	Intent myIntent=null;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
	  // TODO Auto-generated method stub
	  super.onCreate(savedInstanceState);
	  setContentView(R.layout.map);
	  Log.i("MapScreen","onCreate");
	  //RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.mainlayout);
	  mapView = (MapView) findViewById(R.id.mapview);
	  
	  // trying to get the map working better
	  mapView.setSatellite(false);
	  mapView.setDrawingCacheBackgroundColor(-16777216);
	  mapView.setBuiltInZoomControls(true);
	  mapView.setTraffic(false);
	  mapView.setStreetView(false);
	  //mapView.setStreetView(true);
		mapController = mapView.getController();
		mapController.setZoom(16); // Zoom 1 is world view
		
		//setMapLocation(42.3322544, -83.050818 );
		blackMarker = this.getResources().getDrawable(R.drawable.marker);
		itemizedOverlay = new MyItemizedOverlay(blackMarker, mapView);
		locationIcon = this.getResources().getDrawable(R.drawable.radius);
		
		try{
			storeService = ((StoreService)getApplicationContext());
		}catch(Exception e){
			LogUtil.log("mapScreen", "In Exception..............");
			LogUtil.log("mapScreen when storeService are null", e.getMessage());
	}
		
		
    if(stores == null){
    	try{
    		stores = storeService.getStoresListForMap();
    		ArrayList<MyOverlayItem> storeOverlays = new ArrayList<MyOverlayItem>();
    		 // TODO Auto-generated method stub
    		
    		
    		if(stores != null) {
        	for(StoreVO s: stores){
        		storeOverlays.add(MyOverlayItem.create(s, blackMarker));
        	}
        	
        	if(itemizedOverlay != null) {
        		// note addAllOverlays is a much faster way to add Overlays to a map than doing it one at a time.. 
          	itemizedOverlay.addAllOverlays(storeOverlays);
          	mapView.getOverlays().add(itemizedOverlay);
          }
        }
        
    	}catch(Exception e){
      	// cannot get the store List return to homescreen
    		myIntent = new Intent(this, Main.class);
    		startActivityForResult(myIntent, 0);
    		LogUtil.log("mapScreen when stores == null", e.getMessage());
    		e.printStackTrace();
      }
    }
    
	}

	@Override
  protected boolean isRouteDisplayed() {
	  // TODO Auto-generated method stub
	  return false;
  }
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	  // TODO Auto-generated method stub
	  super.onActivityResult(requestCode, resultCode, data);
	  Log.i("MapScreen", "onActivityResult");
	}
	
	@Override
	protected void onResume() {
	  // TODO Auto-generated method stub
	  super.onResume();
	  int selectedStoreId = -1;
	  int overrideStoreId = -1;
	  
	 try{
	  	Bundle bundle = getIntent().getExtras();
	  	selectedMapInent= bundle.getString(INTENT_KEY);
	  	selectedStoreId = bundle.getInt(StoreService.SELECTED_STORE_KEY);
	  	overrideStoreId = bundle.getInt(StoreService.SELECTED_STORE_OVERRIDE);
	  }catch(Exception e){
	  	selectedMapInent =  AppIntent.ISSUE_DETECTED;
	  }
	  
	   /*
	   if(selectedMapInent == null || stores == null)
	  	 selectedMapInent = AppIntent.ISSUE_DETECTED;
	   */
	   LogUtil.log("MapScreen.OnResume", "Intent: " + selectedMapInent);
	  
	   if(selectedMapInent.equals(AppIntent.ISSUE_DETECTED))
	  	 handleBadIntent();
	  	else if(selectedMapInent.equals(AppIntent.SELECT_STORE))
	  	 handleSelectStore(selectedStoreId, overrideStoreId);
	   else if(selectedMapInent.equals(AppIntent.LOCATION))
	  	 handleLocationRequest() ;
	}
	
	// go home
	private void handleBadIntent() {
		 myIntent = new Intent(this, Main.class);
		 startActivityForResult(myIntent, 0);
	}
	
	private void handleSelectStore(int selectedStoreId, int overrideStoreId) {
		
		// turn off location management if it is on
		if(locationManager != null) {
   		 locationManager.removeUpdates(this);
   		 removeCurrentLocationIcon();
   	 }
 	 
		int selectedIndex = -1;
 	 
 	 	 LogUtil.log("Onresume", "selectedStoreId: " + selectedStoreId);
	   if(selectedStoreId >= 0){
	  	 
	  	 for(int i=0;i<stores.size();i++) {
	  		 if(selectedStoreId == stores.get(i).storeId){
	  			 selectedStore = stores.get(i);
	  			 selectedIndex = i;
	  			 break;
	  		 }
	  	 }
	  	 
	  	 if(selectedIndex > -1) {
	  		 
	  		 if(selectedStoreId != overrideStoreId) {
	  			 // Store is apart of a group, add a new overlay item to the screen
	  	  	 StoreVO overrideStore = storeService.getStore(overrideStoreId);
	  	  	 LogUtil.log("Map onResume override details:", overrideStore.name);
	  	  	 List<Overlay> _overlays2 = mapView.getOverlays(); 
	  	  	 MyItemizedOverlay myItemizedOverlay = (MyItemizedOverlay)_overlays2.get(0);
	  	  	 ArrayList<MyOverlayItem> testItems = myItemizedOverlay.getOverLayItems() ;
	  	  	 LogUtil.log("Map onResume override details testItems:", "" + testItems.size());
	  	  	 OverlayItem orig_overlayItem = testItems.get(selectedIndex);
	  	  	 MyOverlayItem overrideOverlayItem = new MyOverlayItem(orig_overlayItem.getPoint(), overrideStore.name, StoreService.getMapAddressLine(overrideStore), overrideStore.storeId);
	  	  	 myItemizedOverlay.setOverrideOverlaytItem(selectedIndex, overrideOverlayItem);
	  	  	 
	  	   }else {
	  	  	 LogUtil.log("Map onResume override details:", "storees are equal");
	  	   }
	  		
	  		 try{
	  			 // Select the Store
		  		 setMapLocation(Double.valueOf(selectedStore.lat), Double.valueOf(selectedStore.lng)); 
		  		 //List overlays =  mapView.getOverlays();
		  		 LogUtil.log("MapScreen.handleSelectStore", "onResume selectedIndex: " + selectedIndex);
		  		 List<Overlay> _overlays = mapView.getOverlays(); 
		  		 LogUtil.log("MapScreen.handleSelectStore", "_overlays " + _overlays.size());
		  		 itemizedOverlay = (MyItemizedOverlay) _overlays.get(0);
		  		 itemizedOverlay.autoSelect(selectedIndex);
		  		 
		  		
		  	 }catch(Exception e){}
		
	  	 }
	  	   	 
	   }
		
	}
	
	private void handleLocationRequest() {
		
	 pd = ProgressDialog.show(this, "Working..","Searching for location", true,false);
 	 setTimer(3000);
 	 if(locationManager == null) {
 		 locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
 		 
 	 }
 	 
 	 Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    String strLocationProvider = locationManager.getBestProvider(criteria, true);
 	 Location lastKnownLocation = locationManager.getLastKnownLocation(strLocationProvider);
 	 
 	 if(lastKnownLocation != null){
 		 if(pd != null)
 	      pd.dismiss();
 		 onLocationChanged(lastKnownLocation);
   }
 	 
 	 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 1000.0f, this);
	}
	
	@Override
	protected void onStart() {
	  // TODO Auto-generated method stub
	  super.onStart();
	  Log.i("MapScreen", "onStart");
	}
	
	private void setMapLocation(double __lat, double __lng) {
		Log.i("MapScrren", "setMapLocation");
		Location location = new Location("TEST");
		// Set to Harrison Township
		location.setLatitude( __lat);
		location.setLongitude(__lng);
		setLocation(location);
	}
	
	private void setLocation(Location location) {
		int _lat = (int) (location.getLatitude() * 1E6);
		int _lng = (int)( location.getLongitude() * 1E6);
		geoPoint = new GeoPoint(_lat,_lng);
		mapController.setCenter(geoPoint); 
	}
	
	private void handleIcon(GeoPoint point) {
		locationItemizedOverlay = new MyLocationOverlay(locationIcon);
		overlayitem = new MyOverlayItem(point, "", "", 0);
		locationItemizedOverlay.addOverlay(overlayitem);
		mapView.getOverlays().add(locationItemizedOverlay);
	}

	public void onLocationChanged(Location location) {
	  // TODO Auto-generated method stub
		if(pd != null)
      pd.dismiss();
		if (location != null) {
			int _lat = (int) (location.getLatitude() * 1E6);
			int _lng = (int)( location.getLongitude() * 1E6);
			geoPoint = new GeoPoint(_lat,_lng);
			mapController.animateTo(geoPoint);
			removeCurrentLocationIcon();
			handleIcon(geoPoint);
		}
	  
  }

	private void removeCurrentLocationIcon() {
	  // TODO Auto-generated method stub
		LogUtil.log("removeCurrent", "" + mapView.getOverlays().size());
		if(mapView.getOverlays().size() > 1){
			mapView.getOverlays().remove(1);
			mapView.invalidate();
		}
	}

	public void onProviderDisabled(String provider) {
	  // TODO Auto-generated method stub
	  
  }

	public void onProviderEnabled(String provider) {
	  // TODO Auto-generated method stub
	  
  }

	public void onStatusChanged(String provider, int status, Bundle extras) {
	  // TODO Auto-generated method stub
	  
  }
	
	
	protected void setTimer( long time )
	{
		locationDurationCheck = 0;
		final long elapse = 1000;
		Runnable t = new Runnable() {
			public void run()
			{
				runNextTask();
				
				if( !isLocationCheckComplete )
	      {
					taskHandler.postDelayed( this, elapse );
	      }else {
	      	taskHandler.removeCallbacks(this);
	      }
			}
		};
		taskHandler.postAtTime( t, time );
	}
	 
	protected void runNextTask()
	{
		// increment number
		locationDurationCheck++;
		if(locationDurationCheck > 10){
			isLocationCheckComplete = true;
			if(pd != null)
	      pd.dismiss();
		}
	}
	
	@Override
  protected void onStop() {
	  // TODO Auto-generated method stub
	  super.onStop();
	  LogUtil.log("MapScreen", "onStop");
	  // Doing users of app  favor and unregister the LocationManager 
	  if(locationManager != null) {
	  	locationManager.removeUpdates(this);
	  	locationManager = null;
	  }
  }
	
	
}
